package com.lanou.tipsy.tools.volley;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.lanou.tipsy.base.BaseApplication;

/**
 * Created by dllo on 15/9/17.
 * Volley单例,保证只有一个请求队列
 */
public class VolleySingleton {

    private static final String TAG = "VolleySingleton";
    private static VolleySingleton volleySingleton;
    private RequestQueue requestQueue;//创建一个Volley的队列
    private Context context;
    private ImageLoader imageLoader; //网络请求图片

    /**
     * 构造方法私有,防止其他类中通过new创建对象
     */
    private VolleySingleton (Context context) {
        this.context = context;
        requestQueue = getRequestQueue();
        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(10 * 1024 * 1024);
            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    /**
     * 获得ImageLoader的get方法
     * @return
     */
    public ImageLoader getImageLoader() {
        return imageLoader;
    }

    /**
     * 创建Volley的静态方法,用于创建对象
     * 提供一个静态方法,获取本类的实例(单例模式)
     * @return
     */
    public static VolleySingleton getInstance () {
        //如果对象还未创建,新建
        if (volleySingleton == null) {
            //保证不会出现内存溢出的问题  application只会有一个
            volleySingleton = new VolleySingleton(BaseApplication.getContext());
        }
        return volleySingleton;
    }

    /**
     * 新建请求队列
     * @return
     */
    private RequestQueue getRequestQueue () {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(context);
        }
        return requestQueue;
    }

    /**
     * 提供一个方法,将Request添加到队列
     * 在请求队列的时候加一个tag值,方便查找
     */
    public <T> void addQueue (Request<T> request) {
        request.setTag(TAG);
        getRequestQueue().add(request);
    }
    public <T> void addQueue (Request<T> request, String tag) {
        request.setTag(tag);
        getRequestQueue().add(request);
    }
    //将Request移出队列,取消网络请求
    public void removeRequest(Object object) {
        getRequestQueue().cancelAll(object);
    }
}